package com.runshu.runshuwulian.ui.fragment;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.snackbar.Snackbar;
import com.hyphenate.easeui.mwidget.brvahrecyclerview.BaseQuickAdapter;
import com.hyphenate.easeui.mwidget.linkagerecyclerview.LinkageRecyclerView;
import com.hyphenate.easeui.mwidget.linkagerecyclerview.bean.DefaultGroupedItem;
import com.runshu.runshuwulian.R;
import com.runshu.runshuwulian.adapter.XiaoHaoAdapter;
import com.runshu.runshuwulian.base.BaseFragment;
import com.runshu.runshuwulian.bean.LabelBean;
import com.runshu.runshuwulian.bean.ParentLabelBean;
import com.runshu.runshuwulian.bean.XiaoHaoListBean;
import com.runshu.runshuwulian.bean.XiaohaoMenuBean;
import com.runshu.runshuwulian.ui.viewhelper.XiaoHaoHelper;
import com.runshu.runshuwulian.utils.LogUtil;
import com.runshu.runshuwulian.utils.StringUtils;
import com.runshu.runshuwulian.widget.CleanEditText;
import com.runshu.runshuwulian.widget.picker.DoubleTimeSelectDialog;
import com.zxl.library.DropDownMenu;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Demo class
 *
 * @author yu
 * @date 11/26/20
 * @decs：
 */

public class XiaoHaoFrg extends BaseFragment {
    @BindView(R.id.dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.et_client_search)
    CleanEditText etSearch;
    private String headers[] = {"全部状态", "全部科室", "时间"};
    private String selectTypeOne[] = {"全部", "出库", "入库"};
    private String selectTypeTwo[] = {"心内一", "心内二"};
    //        0全部", "1最近一个月", "2最近三个月", "3自定义"
    private String selectTypeThree[] = {"全部", "最近一个月", "最近三个月", "自定义"};
    private DoubleTimeSelectDialog mDoubleTimeSelectDialog;

    private View contentView;
    private int[] types = new int[]{DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_CUSTOM, DropDownMenu.TYPE_LIST_CITY};

    private SwipeRefreshLayout swipe_layout;
    private RecyclerView recyclerView;
    private XiaoHaoAdapter mAdapter;
    private List<XiaoHaoListBean.RecordsBean> mData;

    public XiaoHaoHelper helper;

    @Override
    protected int setLayoutId() {
        return R.layout.frg_xiaohao;
    }

    @Override
    protected void initView() {
        super.initView();
        helper = new XiaoHaoHelper( this, selfAct() );
        contentView = getLayoutInflater().inflate( R.layout.content_xiaohao_frg, null );
        swipe_layout = contentView.findViewById( R.id.swipe_layout );
        recyclerView = contentView.findViewById( R.id.recy_xiaohao );

        helper.getListInfo();

    }

    private void initData() {
        mData = new ArrayList<>();
        mAdapter = new XiaoHaoAdapter( mData );
        recyclerView.setLayoutManager( new LinearLayoutManager( context, LinearLayoutManager.VERTICAL, false ) );
//        recyclerView.setAdapter( mAdapter );
        mAdapter.bindToRecyclerView( recyclerView );
        mAdapter.setEmptyView( R.layout.empty_view );
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode( true );
        getView().requestFocus();
        getView().setOnKeyListener( (v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                //退出activity前关闭菜单
                if (mDropDownMenu.isShowing()) {
                    mDropDownMenu.closeMenu();
                    return true;
                } else {
                    return false;
                }
            }
            return false;
        } );
    }


    public void setListData(List<XiaoHaoListBean.RecordsBean> resultEntityList) {
        swipe_layout.setRefreshing( false );
        mAdapter.setNewData( resultEntityList );
        mAdapter.loadMoreComplete();
        if (resultEntityList == null || resultEntityList.size() == 0) {
            mAdapter.setEmptyView( R.layout.empty_view );
        }

    }

    public void addListData(List<XiaoHaoListBean.RecordsBean> resultEntityList) {
        swipe_layout.setRefreshing( false );
        if (resultEntityList == null || resultEntityList.size() == 0) {
            mAdapter.loadMoreEnd();
            return;
        }
        mAdapter.addData( resultEntityList );
        mAdapter.loadMoreComplete();
    }


    /**
     * 设置类型和数据源：
     * DropDownMenu.KEY对应类型（DropDownMenu中的常量，参考上述核心源码）
     * DropDownMenu.VALUE对应数据源：key不是TYPE_CUSTOM则传递string[],key是TYPE_CUSTOM类型则传递对应view
     */
    private List<HashMap<String, Object>> initViewData() {
        List<HashMap<String, Object>> viewDatas = new ArrayList<>();
        HashMap<String, Object> map;
        for (int i = 0; i < headers.length; i++) {
            map = new HashMap<String, Object>();
            map.put( DropDownMenu.KEY, types[i] );
            if (i == 0) {
                map.put( DropDownMenu.VALUE, selectTypeOne );
//                map.put(DropDownMenu.SELECT_POSITION, 1);

            } else if (i == 1) {
                map.put( DropDownMenu.VALUE, selectTypeTwo );
//                map.put(DropDownMenu.SELECT_POSITION, 0);

            } else {
                map.put( DropDownMenu.VALUE, selectTypeThree );
//                map.put(DropDownMenu.SELECT_POSITION,2);

            }
            viewDatas.add( map );
        }
        return viewDatas;
    }

    private void bindListener() {
        //该监听回调只监听默认类型，如果是自定义view请自行设置，参照demo
        mDropDownMenu.addMenuSelectListener( (index, pos, clickstr) -> {
            //index:点击的tab索引，pos：单项菜单中点击的位置索引，clickstr：点击位置的字符串
            LogUtil.e( TAG, "===index==" + index + "pos====" + pos );
            if (index == 0) {
                try {
                    List<LabelBean> statusList = xiaohaoMenuBean.getStatusList();
                    if (statusList == null) {
                        showShortToast( "获取状态列表失败" );
                        return;
                    }
                    helper.getParams().put( "orderStatus", statusList.get( pos ).getValue() );
                    helper.setParams( helper.getParams() );
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (index == 1) {

            } else if (index == 2) {
                List<LabelBean> statusList = xiaohaoMenuBean.getTimeList();
                if (statusList == null) {
                    showShortToast( "获取时间列表失败" );
                    return;
                }
                if ("自定义".equals( statusList.get( pos ).getLabel() )) {
                    showCustomTimePicker();
                } else {
                    try {
                        helper.getParams().put( "type", statusList.get( pos ).getValue() );
                        helper.setParams( helper.getParams() );
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

        } );


        swipe_layout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                helper.refreshData();
            }
        } );

        mAdapter.setOnLoadMoreListener( new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                helper.loadMore();
            }
        } );
        swipe_layout.setRefreshing( true );
        swipe_layout.post( () -> {
            helper.refreshData();

        } );

    }

    private void showCustomTimePicker() {
        /**
         * 默认的周开始时间，格式如：yyyy-MM-dd
         **/
        String defaultWeekBegin = "";
        /**
         * 默认的周结束时间，格式如：yyyy-MM-dd
         */
        String defaultWeekEnd = "";

        String beginDeadTime = "1970-01-01";
        if (mDoubleTimeSelectDialog == null) {
            mDoubleTimeSelectDialog = new DoubleTimeSelectDialog( getActivity(), beginDeadTime, defaultWeekBegin, defaultWeekEnd );
            mDoubleTimeSelectDialog.setOnDateSelectFinished( (startTime, endTime) -> {
                mDropDownMenu.setTabText( 2, StringUtils.getMMdd( startTime ) + "至" + StringUtils.getMMdd( endTime ) );
                try {
                    helper.getParams().put( "createTimeBefore", startTime );
                    helper.getParams().put( "createTimeAfter", endTime );
                    helper.getParams().put( "type", "6" );
                    helper.setParams( helper.getParams() );
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } );

            mDoubleTimeSelectDialog.setOnDismissListener( dialog -> {
            } );
        }
        if (!mDoubleTimeSelectDialog.isShowing()) {
            mDoubleTimeSelectDialog.recoverButtonState();
            mDoubleTimeSelectDialog.show();
        }
    }

    XiaohaoMenuBean xiaohaoMenuBean;

    public void initMenu(XiaohaoMenuBean xiaohaoMenuBean) {
        this.xiaohaoMenuBean = xiaohaoMenuBean;
        List<LabelBean> statusList = xiaohaoMenuBean.getStatusList();
        List<String> list = new ArrayList<>();
        for (LabelBean status : statusList) {
            list.add( status.getLabel() );
        }
        selectTypeOne = list.toArray( new String[list.size()] );

        List<LabelBean> statusList2 = xiaohaoMenuBean.getTimeList();
        List<String> list2 = new ArrayList<>();
        for (LabelBean status : statusList2) {
            list2.add( status.getLabel() );
        }
        selectTypeThree = list2.toArray( new String[list.size()] );

        mDropDownMenu.setDropDownMenu( Arrays.asList( headers ), initViewData(), contentView, setSecondaryList( 1 ) );
        initData();
        bindListener();
    }

    private View setSecondaryList(final int index) {
        LayoutInflater li = LayoutInflater.from( getContext() );
        View v = li.inflate( R.layout.layout_linkage, null );
        LinkageRecyclerView linkage = v.findViewById( R.id.linkage );
        List<ParentLabelBean> departmentList = xiaohaoMenuBean.getDepartmentList();
        List<DefaultGroupedItem> datas = new ArrayList<>();
        for (ParentLabelBean labelBean : departmentList) {
            datas.add( new DefaultGroupedItem( true, labelBean.getLabel(), labelBean.getValue() ) );
            if (labelBean.getChildren() != null) {
                for (LabelBean tmp : labelBean.getChildren()) {
                    datas.add( new DefaultGroupedItem( new DefaultGroupedItem.ItemInfo( tmp.getLabel(), labelBean.getLabel(), tmp.getValue(), null ) ) );
                }
            }
        }
        linkage.init( datas );
        linkage.setScrollSmoothly( false );
        linkage.setDefaultOnItemBindListener(
                (primaryHolder, primaryClickView, title) -> {
                    Snackbar make = Snackbar.make( primaryClickView, title, Snackbar.LENGTH_SHORT );
                    make.show();
                },
                (primaryHolder, title) -> {
                    //TODO
                },
                (secondaryHolder, item) -> {
                    secondaryHolder.getView( R.id.level_2_item ).setOnClickListener( v1 -> {
                        mDropDownMenu.setTabText( mDropDownMenu.current_tab_position, item.info.getTitle() );
                        mDropDownMenu.lis.onSelectDefaultMenu( index, 0, item.header );
                        mDropDownMenu.closeMenu();
                        try {
                            helper.getParams().put( "departmentId", item.info.getId() );
                            helper.setParams( helper.getParams() );
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } );
                },
                (headerHolder, item) -> {
                    //TODO
                },
                (footerHolder, item) -> {
                    //TODO
                }
        );

        return v;
    }

    @OnClick({R.id.tv_search})
    public void clickView(View v) {
        switch (v.getId()) {
            case R.id.tv_search:
                String s = etSearch.getText().toString();
                if (helper.getParams().has( "consumeNumber" ) && TextUtils.isEmpty( s )) {
                    helper.getParams().remove( "consumeNumber" );
                    helper.setParams( helper.getParams() );
                    return;
                }
                if (TextUtils.isEmpty( s )) {
                    showShortToast( "请输入消耗单号" );
                    return;
                }
                try {
                    helper.getParams().put( "consumeNumber", s );
                    helper.setParams( helper.getParams() );
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}